package uk.co.accolade.clash.core.message;

import uk.co.accolade.clash.core.ClashFilePath;
import uk.co.accolade.clash.core.UserChanges;
import uk.co.accolade.clash.core.Username;

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

public class MessageParser_V1 implements MessageParser {

    private Username username;

    public UserChanges parse( String message ) {
        DataToken[] tokens = DataToken.tokensFromMessage( message );
        username = extractUsername( tokens );
        return extractUserChanges( tokens );
    }

    private UserChanges extractUserChanges( DataToken[] tokens ) {
        List<ClashFilePath> changes = new ArrayList<ClashFilePath>();
        for( DataToken token : tokens ) {
            if( token.key.equals( "filename" ) ) {
                changes.add( new ClashFilePath(token.value) );
            }
        }
        return new UserChanges( username, changes );
    }

    private Username extractUsername( DataToken[] tokens ) {
        for( DataToken token : tokens ) {
            if( token.key.equals( "username" ) ) {
                return new Username(token.value);
            }
        }
        return null;
    }

    public String marshal( UserChanges changes ) {
        StringBuilder b = new StringBuilder("v1::");
        addUsername( changes, b );
        addFileChanges( changes, b );
        return b.toString();
    }

    private void addUsername( UserChanges changes, StringBuilder b ) {
        b.append("username:");
        b.append( changes.getUsername() );
        b.append( ":" );
    }

    private void addFileChanges( UserChanges changes, StringBuilder b ) {
        Iterator<ClashFilePath> files = changes.getChangedFilesReadOnly().iterator();
        while(files.hasNext()) {
            b.append( "filename:" );
            b.append( files.next() );
            if(files.hasNext()) {
                b.append(":");
            }
        }
    }
}
